import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
 
 
class CellTextAlignment(QWidget):
    def __init__(self):
        super(CellTextAlignment, self).__init__()
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle('设置单元格的文本对齐方式')
        self.resize(430, 230)
 
        layout = QHBoxLayout()
        #表格对象
        tableWidget=QTableWidget()
        #四行三列
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        #设置表格字段
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])
 
        newItem=QTableWidgetItem('小明')
        #下面说的对齐与显示都是指在单元格中
        # 右对齐 底端显示，即右下，Qt.AlignRight默认是右上
        newItem.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
        tableWidget.setItem(0,0,newItem)
        #中心对齐，底部显示
        newItem = QTableWidgetItem('男')
        newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignBottom)
        tableWidget.setItem(0, 1, newItem)
        newItem = QTableWidgetItem('190')
        newItem.setTextAlignment(Qt.AlignRight)
        tableWidget.setItem(0, 2, newItem)
 
        layout.addWidget(tableWidget)
        self.setLayout(layout)
 
 
if __name__=='__main__':
    app=QApplication(sys.argv)
    main=CellTextAlignment()
    main.show()
    sys.exit(app.exec_())
 
